package com.heying.springbootweb.controller;

import com.heying.springbootweb.entity.Course;
import com.heying.springbootweb.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

@Controller
@RequestMapping("/cou")//一级路径
@Slf4j
public class CourseController {

    private List<Course> courses;


    {
        courses = new ArrayList<>();
        courses.add(new Course(1,"1001","高数","44","images//mm.jpg"));
        courses.add(new Course(2,"1002","线代","55","images//mm.jpg"));
        courses.add(new Course(3,"1003","英语","66","images//mm.jpg"));
        courses.add(new Course(4,"1004","马原","77","images//mm.jpg"));
        courses.add(new Course(5,"1005","毛概","88","images//mm.jpg"));
    }

    @GetMapping("/queryall")
    public String queryAll(Model model){
        model.addAttribute("courses",courses);
        return "cou/courselist";//request.getRequestDispatcher("url").forward(request.response)
    }

    @GetMapping("/toadd")
    public String toAdd(Model model){
        model.addAttribute("cou", new Course());
        return "cou/addone";
    }

    @PostMapping("/addone")
    public String addOne(Course cou, @RequestPart("photo") Part photo) throws IOException {
        log.info("cou is {}",cou);
        log.debug("submitName is {}",photo.getSubmittedFileName());
        log.debug("contextType is {}",photo.getContentType());
        log.debug("fileSize is {}",photo.getSize());
        String path = CourseController.class.getClassLoader().getResource("").getPath();
        System.out.println(path);
        photo.write(path+ File.separator +"static//cou//images//"+photo.getSubmittedFileName());
        cou.setId(courses.stream().mapToInt(Course::getId).max().orElse(0)+1);
        cou.setImg("images//"+photo.getSubmittedFileName());
        courses.add(cou);
        log.info("cou is {}",courses);
        return "main";
    }

    @GetMapping("tomod")
    public String toMod(@RequestParam("id") Integer id, Model model){
        Course course = courses.stream()
                .filter(s->s.getId().equals(id)).findFirst().orElse(null);
        if(null ==course){
            throw new NoSuchElementException();
        }
        model.addAttribute("cou", course);
        return "cou/modone";
    }

    @PostMapping("/modone")
    public String modOne(Course cou){
        courses.stream().
                filter(s->s.getId().equals(cou.getId())).findFirst().
                ifPresent(s-> BeanUtils.copyProperties(cou,s));
        log.debug("new courses is {}",courses);
        return "main";
    }



}
